package main

import (
	"fmt"
	"go-weiqi-system/config"
	"go-weiqi-system/internal/routes"
	"log"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("Warning: .env file not found, using system environment variables")
	}

	// 加载配置
	cfg := config.Load()

	// 初始化数据库
	if err := config.InitDB(cfg); err != nil {
		log.Fatal("Failed to initialize database:", err)
	}

	// 设置 Gin 模式
	if !cfg.Debug {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建 Gin 引擎
	r := gin.Default()

	// 配置静态文件
	r.Static("/uploads", "./uploads")
	r.StaticFile("/api-doc.html", "./public/api-doc.html")
	r.StaticFile("/admin-login.html", "./public/admin-login.html")

	// 首页重定向到API文档
	r.GET("/", func(c *gin.Context) {
		c.Redirect(302, "/api-doc.html")
	})

	// 初始化路由
	routes.InitRoutes(r, cfg)

	// 启动服务
	addr := fmt.Sprintf(":%d", cfg.Port)
	fmt.Printf("\n🚀 Server is running at http://localhost%s\n", addr)
	fmt.Printf("📖 API Documentation: http://localhost%s/api-doc.html\n", addr)
	fmt.Printf("🔐 Admin Login: http://localhost%s/admin-login.html\n\n", addr)

	if err := r.Run(addr); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}
